const express = require('express');
const bodyParser = require('body-parser');
const user = require('../db/user.js');
const article = require('../db/article');
const album = require('../db/album');
const comment = require('../db/comment');
const Msg = require('../db/msg');
const multer = require('multer');
const fs = require('fs');
const validator = require('validator');
const  wc = require('sensitive-word-filter');

//IP地址
let os = require('os');
let getIPAddress = function () {
    let ifaces = os.networkInterfaces();
    let ip = '';
    for (let dev in ifaces) {
        ifaces[dev].forEach(function (details) {
            if (ip === '' && details.family === 'IPv4' && !details.internal) {
                ip = details.address;
                return;
            }
        });
    }
    return ip || "127.0.0.1";
};

let MD=require('../util').MD;


//请求频次处理
const rateLimit = require("express-rate-limit");


const createAccountLimiter = rateLimit({
    windowMs: 60 * 1000, // 1 hour window
    max: 10, // start blocking after 5 requests
    message:
        "当前IP地址请求过于频繁，请于1分钟候后重试"
});

const router = express.Router();

//注册
router.post('/register', function (req, res) {
    let username = req.body.username;
    let password = req.body.password;
    let email = req.body.email;
    user.find({username: username}, function (err, data) {
        if (err) {
            console.log(err);
            res.send('500服务器内部错误');
            return;
        }
        if (!data.length) {
            let person = new user({
                    username: username,
                    password: MD(password),
                    email: email,
                }
            );

            person.save(function (err) {
                if (!err) {
                    res.send('注册成功！！')
                }
            })

        }
        else {
            res.send('用户名已存在');
        }
    });

});


//登录页
router.get('/login.html', function (req, res) {
    if (req.session.login) {
        res.redirect('/admin/info')
    } else {
        res.render('login.html');
    }
});

//登录逻辑
router.post('/login', function (req, res) {
    let username = req.body.username,
        password = MD(req.body.password);
    user.find({username: username, password: password}, function (err, data) {
        if (err) {
            console.log(err);
        }
        else {
            if (data.length == 0) {
                res.send('登录失败')
            }
            else {
                req.session.login = true;
                req.session.userid = data[0]._id;
                res.redirect('/admin/info');
            }
        }
    })
});
//登出
router.get('/loginout', function (req, res) {
    req.session.login = false;
    res.redirect('/');
});


//前台文章详情
router.get('/article/:id.html', (req, res) => {
    let id = req.params.id;
    article.find({_id: id}, function (err, data) {
        if (!err) {
            if (data.length) {
                data[0].num += 1;
                data[0].save();
                comment.find({articleId: id}, function (err2, data2) {
                    res.render('blog/detail.html', {
                        data: data[0],
                        comment: data2
                    })
                });

            }
            else {
                res.send('没找到这篇文章哟~')
            }
        }
        else {
            res.send(err);
        }
    });
});


//添加评论
router.post('/add/comment', createAccountLimiter, function (req, res) {
    geeValidator(req, res, {
        pass: function () {
            if (req.body.email && req.body.content) {
                if (!validator.isEmail(req.body.email)) {
                    res.json({status: false, msg: '留言失败！请填写合法的邮箱地址'});
                    return
                }

                let timeStamp = new Date();
                let msg = {
                    email: wc.filter(req.body.email),
                    content:wc.filter(req.body.content),
                    time: timeStamp.getTime(),
                    addTime: timeStamp.toLocaleString(),
                    articleId: req.body.id,
                    articleTitle: req.body.title,
                    pass: false
                };

                new comment(msg).save().then(function (err) {
                    res.json({status: true, msg: '留言成功！'});
                });
            }
            else {
                res.json({status: false, msg: '留言失败，内容不得为空！'});
            }
        },
        fail: function () {
            res.json({status: false, msg: '提交失败'});
        }
    });
});


//后台评论管理

router.get('/admin/comment/:page', (req, res) => {
    if (!req.session.login) {
        res.redirect('/login.html');
        return 0;
    }
    else {
        let page = req.params.page;
        let pageNum = 10;
        comment.count({}, function (err, counts) {
            let PageTotal = (Math.ceil(counts / pageNum));
            if(PageTotal===0)
            {
                res.render('admin/admin-comment.html',{
                    comment:'',
                    current: 8
                });
                return;
            }
            if (page > PageTotal) {
                res.redirect('/admin/comment/' + PageTotal);
                return;
            }
            comment.find({}).limit(pageNum).skip((page - 1) * pageNum).exec((err, data) => {
                if (!err) {
                    res.render('admin/admin-comment.html', {
                        login: req.session.login,
                        comment: data,
                        page: {
                            current: Number(page),
                            total: PageTotal,
                            path: 'admin/comment'
                        },
                        current: 8
                    })
                }
            })
        });
    }

});

//删除评论

router.get('/delete/comment/:id', (req, res) => {
    let id = req.params.id;
    comment.remove({_id: id}, (err) => {
        if (!err) {
            res.json({status: true, msg: '删除成功'});
        }
        else {
            res.json({status: false, msg: err});
        }
    });
});


//获取评论详情
router.get('/getComment/:id',(req,res)=>{
    let id=req.params.id;
    comment.find({_id:id},(err,data)=>{
        err?res.json({status:false,data:err}):res.json({status:true,data:data[0]});
    })
});
//回复评论
router.post('/responseComment/:id',(req,res)=>{
    let id=req.params.id;
    let timeStamp=new Date();
    let data={
        email:req.body.email,
        as:req.body.as,
        content:req.body.response,
        time:timeStamp.getTime(),
        addTime:timeStamp.toLocaleString()
    };

    comment.update({_id:id},{response:data},(err)=>{
        res.json({status:true})
    });


});


//个人信息管理
router.get('/admin/info', function (req, res) {
    if (!req.session.login) {
        res.redirect('/login.html');
        return 0;
    }
    else {
        user.find({}, function (err, data) {
            res.render('admin/admin-info.html', {
                login: req.session.login,
                headpic: data[0].headpic,
                intro: data[0].intro,
                current: 1
            })
        });
    }
});


//写文章页面
router.get('/admin/article/add', function (req, res) {
    if (!req.session.login) {
        res.redirect('/login.html');
        return 0;
    } else {
        res.render('admin/admin-edit.html',{
            current:2
        });

    }
});

//文章管理
router.get('/admin/article/:page', function (req, res) {

    if (!req.session.login) {
        res.redirect('/login.html');
        return 0;
    }
    else {
        let page = req.params.page;
        let pageNum = 10;
        article.count({}, function (err, counts) {
            let PageTotal = (Math.ceil(counts / pageNum));
            if(PageTotal===0)
            {
                res.render('admin/admin-article.html',{article:'',current:2});
                return;
            }
            if (page > PageTotal) {
                res.redirect('/admin/article/' + PageTotal);
                return;
            }
            article.find({}).limit(pageNum).skip((page - 1) * pageNum).exec((err, data) => {
                if (!err) {
                    res.render('admin/admin-article.html', {
                        login: req.session.login,
                        article: data,
                        page: {
                            current: Number(page),
                            total: PageTotal,
                            path: 'admin/article'
                        },
                        current: 2
                    })
                }

            })
        });
    }
});

//接收文章
router.post('/addArticle', function (req, res) {
    let time = new Date();
    let articleId = req.body.id;
    if (articleId) {
        article.update({_id: articleId}, req.body, function (err, data) {
            if (!err) {
                res.json({
                    status: true,
                    msg: '更新成功',
                    redirect: '/admin/article/1'
                })
            }
        });
    }
    else {
        req.body.addTime = time.toLocaleString();
        req.body.num = 0;
        req.body.author = req.session.userid;
        new article(req.body).save().then(function () {
            res.json({status: true, msg: '发布成功', redirect: '/admin/article/1'});
        });
    }
});

//删除文章
router.get('/delete/article/:id', function (req, res) {
    let id = req.params.id;
    article.remove({_id: id}, function (err, data) {
        if (!err) {
            res.send({status: true, msg: '删除成功', redirect: '/admin/article/1'});
        }
        else {
            res.send({status: false, msg: '删除失败'});
        }
    })
});

//编辑文章
router.get('/admin/article/edit/:id', function (req, res) {
    if (!req.session.login) {
        res.redirect('/login.html')
    }
    else {
        let id = req.params.id;
        article.find({_id: id}, function (err, data) {
            res.render('admin/admin-edit.html', {
                data: data[0]
            });
        });
    }
});

//前台默认首页
router.get('/', (req, res) => {
    res.render('./home/index.html',{})
    // res.redirect('/index/1')

});

router.get('/index/:page', (req, res) => {
    //页码
    let page = req.params.page;
    //每页数量
    let pageNum = 10;
    user.find({}, function (err, data) {
        article.count({}, function (err, counts) {
            //总页数
            let PageTotal = (Math.ceil(counts / pageNum));

            if(PageTotal==0)
            {
                res.render('blog/index.html',{
                    data: '',
                    headpic: data[0].headpic,
                    intro: data[0].intro
                });
                return;
            }


            if (page > PageTotal) {
                res.redirect('/index/' + PageTotal);
                return;
            }
            article.find({}).limit(pageNum).skip((page - 1) * pageNum).exec((err, data2) => {
                if (!err) {
                    res.render('blog/index.html', {
                        data: data2,
                        headpic: data[0].headpic,
                        intro: data[0].intro,
                        page: {
                            current: Number(page),
                            total: PageTotal,
                            path: 'index'
                        },
                        title: '买文博的个人博客'
                    })
                }
            })
        });

    });
});



//注册页面
router.get('/register.html', (req, res) => {
    res.render('register.html')
});

//上传配置项
let storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/upload')
    },
    filename: function (req, file, cb) {
        let time = new Date().getTime();
        let path = `${time}.` + file.mimetype.split('/')[1];
        cb(null, path, new album({path: `/static/upload/${path}`, addTime: time, fileName: path}).save())
    }
});
//依赖multer模块
let upload = multer({storage: storage});//初始化upload函数，供上传文件使用

//修改个人简介接口
router.post('/admin/info/edit', (req, res) => {
    if (!req.session.login) {
        res.json({
            status: false,
            redirect: '/login.html',
            msg: '请登录'
        })
    }
    else {
        let id = req.session.userid;
        let headpic = req.body.headpic;

        user.update({_id: id}, {intro: req.body.intro, headpic: headpic}).then(function () {
            res.json({status: true, msg: '修改个人信息成功', redirect: '/admin/info'})
        })
    }

});


//读取图册接口
router.get('/admin/album/:page', (req, res) => {
    let page = req.params.page;
    album.count({}, function (err, count) {
        album.find({}).skip(20 * (page - 1)).limit(20).exec(function (err, data) {
            res.render('admin/admin-album.html', {
                data: data,
                page: {
                    current: page,
                    total: Math.ceil(count / 20),
                    path: 'admin/album'
                },
                current: 3
            });
        })
    });


});


//上传图片
router.post('/upload/img', upload.single('img'), (req, res) => {
    res.send({status: true, data: `/static/upload/${req.file.filename}`, redirect: '/admin/album/1'});
});
//删除图片接口
router.get('/delete/img/:id', (req, res) => {
    let _id = req.params.id;
    album.find({_id: _id}, (err, data) => {
        if (!err) {
            if (data.length) {
                let path = `./public/upload/${data[0].fileName}`;
                let flag = fs.existsSync(path);
                if (flag) {
                    fs.unlinkSync(path);
                    album.remove({_id: _id}, function (err, data) {
                        if (!err) {
                            res.json({status: true, msg: "删除成功", redirect: '/admin/album/1'});
                        }
                        else {
                            res.json({status: false, msg: `删除失败${err}`, redirect: '/admin/album/1'})
                        }
                    })
                } else {
                    album.remove({_id: _id}, function (err, data) {
                    });
                    res.json({status: true, msg: "删除失败，图片不存在", redirect: '/admin/album/1'})
                }
            }
            else {
                res.json({status: true, msg: "删除失败，图片不存在", redirect: '/admin/album'})
            }
        }
        else {
            res.json({status: false, msg: `删除失败${err}`})
        }
    });
});


//图库弹窗
router.get('/album/lib/:page', (req, res) => {
    let page = req.params.page;
    album.count({}, function (err, count) {
        album.find({}).skip(10 * (page - 1)).limit(10).exec(function (err, data) {
            if (!err) {

                let _html = '';
                data.forEach(function (e, i) {
                    _html += `<li data-url="${e.path}"><i></i><div class="img-box"><img src="${e.path}" alt=""></div></li>`
                });

                let _page = '';
                for (let i = 0; i < Math.ceil(count / 10); i++) {
                    if (i + 1 == page) {
                        _page += `<a href="javascript:;"  class="current" data-url="/album/lib/${i + 1}">${i + 1}</a>`
                    }
                    else {
                        _page += `<a href="javascript:;"  data-url="/album/lib/${i + 1}">${i + 1}</a>`
                    }
                }

                let sendData = {
                    content: _html,
                    upage: _page
                };
                res.json({status: true, data: sendData})
            }

        });

    })
});

//前台留言页面
router.get('/msg', (req, res) => {
    res.render('msg.html')
});

//删除留言
router.get('/delete/msg/:id', (req, res) => {
    let id = req.params.id;
    Msg.remove({_id: id}, (err, data) => {
            if (!err) {
                res.json({
                    status: true,
                    redirect: '/admin/msg/1'
                })
            }
            else {
                res.json({
                    status: false,
                    msg: '删除失败',
                    redirect: '/admin/msg/1'
                })
            }
        }
    )
});


router.get('/admin/msg/:page', (req, res) => {
    let page = req.params.page;
    let pageNum = 10;
    Msg.count({}, function (err, counts) {
        let PageTotal = (Math.ceil(counts / pageNum));
        if(PageTotal==0)
        {
            res.render('admin/admin-msg.html',{
                data:0,
                current:4
            });
            return;
        }
        if (page > PageTotal) {
            res.redirect('/admin/msg/' + PageTotal);
            return;
        }
        Msg.find({}).limit(pageNum).skip((page - 1) * pageNum).exec((err, data2) => {
            if (!err) {
                res.render('admin/admin-msg.html', {
                    data: data2,
                    page: {
                        current: Number(page),
                        total: PageTotal,
                        path: 'admin/msg'
                    },
                    current: 4
                })
            }
        })
    });
});


router.get('/admin/setting', (req, res) => {
    res.render('admin/admin-setting.html', {
        current: 5
    });
});
router.get('/admin/data', (req, res) => {
    if (!req.session.login) {
        res.redirect('/login.html');
        return 0;
    }
    res.render('admin/admin-data.html', {
        current: 6
    });
});
//导出数据
router.get('/export/data/:type', (req, res) => {
    if (!req.session.login) {
        res.redirect('/login');
        return 0;
    }
    let type = req.params.type;
    let model;
    switch (type) {
        case 'article':
            model = article;
            break;
        case 'album':
            model = album;
            break;
    }
    model.find({}, function (err, data) {
        let time = new Date().toLocaleString();
        res.set({
            'Content-Type': 'application/octet-stream',
            'Content-Disposition': `attachment; filename=${type}-${time}.json`
        });
        res.send(JSON.stringify(data));
    })
});
//导出数据
router.get('/import/data/:type', (req, res) => {
    if (!req.session.login) {
        res.redirect('/login');
        return 0;
    }
});


//拉取更新文件
const process = require('child_process');
//重启页面
router.get('/admin/reboot', (req, res) => {
    if (!req.session.login) {
        res.redirect('/login.html');
    }
    else {
        res.render('admin/admin-reboot.html', {
            current: 7
        })
    }
});



router.get('/reboot', (req, res) => {
    process.exec('git pull');
    setTimeout(function () {
        process.exec('pm2 restart 0');
    }, 5000);
    res.json({status:true})
});


function geeValidator(req, res, callbacks) {
    click.validate(req.session.fallback, {
        geetest_challenge: req.body.geetest_challenge,
        geetest_validate: req.body.geetest_validate,
        geetest_seccode: req.body.geetest_seccode
    }, function (err, success) {
        if (err) {
            res.send({
                status: "error",
                msg: err
            });
        } else if (!success) {
            // 二次验证失败
            callbacks && callbacks.fail && callbacks.fail();
        } else {
            callbacks && callbacks.pass && callbacks.pass();
        }
    });
}

//获取验证串串
let click = require('../geetest/click');
router.get("/jigsaw", function (req, res) {
    click.register(null, function (err, data) {
        if (err) {
            console.error(err);
            res.status(500);
            res.send(err);
            return;
        }
        if (!data.success) {
            req.session.fallback = true;
            res.send(data);

        } else {
            req.session.fallback = false;
            res.send(data);
        }
    });
});


module.exports = router;
